<template>
  <div class="e-main mainWindow flex flex-col">
    <!--    标题栏  -->
    <div class="e-header flex flex-col relative items-center">
      <img alt="" class="mt-2 absolute" src="../assets/headerTextLogo.png" />
      <div class="mt-1.5 flex w-full justify-between items-center gap-1">
        <!-- 添加 gap-1 减少间距 -->
        <div class="flex gap-1">
          <a-dropdown>
            <a-button class="rounded-3xl w-28 flex gap-1 justify-center">
              患者信息
            </a-button>
            <template #overlay>
              <a-menu @click="handlePatientMenuClick">
                <a-menu-item key="1">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1">新增患者 <img alt=""
                      src="../assets/buttonIcon/addUser.svg" /></a-button>
                </a-menu-item>
                <a-menu-item key="2">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1">修改信息 <img alt=""
                      src="../assets/buttonIcon/editUser.svg" /></a-button>
                </a-menu-item>
                <a-menu-item key="3">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1">删除患者 <img alt=""
                      src="../assets/buttonIcon/deleteUser.svg" /></a-button>
                </a-menu-item>
                <a-menu-item key="4">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1">保存患者 <img alt=""
                      src="../assets/buttonIcon/saveUser.svg" /></a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
          <a-dropdown>
            <a-button class="rounded-3xl w-28 flex gap-1 justify-center">
              检查部位
            </a-button>
            <template #overlay>
              <a-menu @click="handleCheckMenuClick">
                <a-menu-item key="1">
                  <div class="flex items-center">
                    <a-button class="bg-white rounded-3xl w-28 flex gap-1" v-model:value="userForm.checkPart"
                      :options="partOptions" @change="handlePartsChange" style="width: 100%">耳部</a-button>
                  </div>
                </a-menu-item>
                <a-menu-item key="2">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1" v-model:value="userForm.checkPart"
                    :options="partOptions" @change="handlePartsChange" style="width: 100%">鼻部</a-button>
                </a-menu-item>
                <a-menu-item key="3">
                  <a-button class="bg-white rounded-3xl w-28 flex gap-1" v-model:value="userForm.checkPart"
                    :options="partOptions" @change="handlePartsChange" style="width: 100%">咽喉部</a-button>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>

        <div class="left-0  flex gap-2 ml-5">
          <a-button class="bg-white rounded-3xl w-28 flex gap-1" @click="openSearchModal">检索病人 <img alt=""
              src="../assets/buttonIcon/searchPatient.svg" /></a-button>
        </div>
        <div class="right-0  flex gap-2 mr-5">
          <a-button class="bg-white rounded-3xl w-24 flex gap-1 justify-center" @click="previewReport">预览 <img alt=""
              src="../assets/buttonIcon/preview.svg" /></a-button>
          <a-button class="bg-white rounded-3xl w-24 flex gap-1 justify-center">打印 <img alt=""
              src="../assets/buttonIcon/print.svg" /></a-button>
          <a-button class="bg-white rounded-3xl w-36 flex gap-1 justify-center">
            医生ID：{{ doctor.name }}
            <a-dropdown placement="bottomRight">
              <img alt="" src="../assets/buttonIcon/doctor.svg" />
              <template #overlay>
                <a-menu>
                  <a-menu-item key="1" @click="addDoctor">
                    <UserOutlined />
                    医生注册
                  </a-menu-item>
                  <a-menu-item key="2" @click="updateDoctor">
                    <UserOutlined />
                    医生修改
                  </a-menu-item>
                  <a-menu-item key="3" @click="delDoctor">
                    <UserOutlined />
                    医生删除
                  </a-menu-item>
                  <a-menu-item key="3" @click="logout">
                    <UserOutlined />
                    切换医生
                  </a-menu-item>
                </a-menu>
              </template>
            </a-dropdown>
          </a-button>
          <!--          <a-popconfirm cancel-text="取消" ok-text="确认" title="是否要退出登录" @confirm="logout">-->
          <!--            <a-button class="bg-white rounded-3xl w-28 flex gap-1 justify-center"-->
          <!--            >系统设置 <img src="../assets/buttonIcon/setting.svg" alt=""-->
          <!--            /></a-button>-->
          <!--          </a-popconfirm>-->

          <a-dropdown>
            <a-button class="rounded-3xl w-28 flex gap-1 justify-center" >
              系统设置 <img alt="" src="../assets/buttonIcon/setting.svg" />
            </a-button>
            <template #overlay>
              <a-menu @click="handleSettingMenuClick">
                <a-menu-item key="1">
                  <HomeOutlined />
                  修改医院名称
                </a-menu-item>
                <a-menu-item key="2">
                  <LogoutOutlined />
                  退出登录
                </a-menu-item>
              </a-menu>
            </template>
            <template #icon>
              <SettingOutlined />
            </template>
          </a-dropdown>

          <a-button class="bg-white rounded-3xl w-28 flex gap-1 justify-center shutdown text-white" @click="closeWin">
            退出系统
            <img alt="" src="../assets/buttonIcon/shutdown.svg" /></a-button>
        </div>
      </div>
      <img alt="" class="" src="../assets/headerLine.png" />

    </div>
    <!--          表单和table区--begin-->
    <div class="e-content flex grow ">
      <div class="e-one w-1/4 h-full items-stretch p-2">
        <div class="e-form h-2/7 p-2">
          <div class="bg-white h-full rounded-2xl p-5 flex flex-col gap-2">
            <div v-if="false" class="flex items-center justify-center">
              <span>检查ID：</span>
              <a-input v-model:value="userForm.checkId"></a-input>
            </div>
            <div v-if="false" class="flex items-center justify-center">
              <span>检查ID：</span>
              <a-input v-model:value="userForm.userId"></a-input>
            </div>
            <div class="flex items-center">
              <span class="text-nowrap">检查序号：</span>
              <!--              <a-input v-model="userForm.checkSerial" disabled></a-input>-->
              <a-input v-model:value="userForm.checkSerial" disabled></a-input>
            </div>
            <div class="flex items-center">
              <span class="text-nowrap">患者姓名：</span>
              <a-input v-model:value="userForm.checkName" :disabled="disableForm" class="mr-2"></a-input>
              <span class="text-nowrap">性别：</span>
              <a-select v-model:value="userForm.checkSex" :disabled="disableForm" style="width: 500px">
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>
              </a-select>
            </div>
            <div class="flex items-center">
              <span class="text-nowrap">检查日期：</span>
              <a-date-picker v-model:value="userForm.checkDate" :disabled="disableForm" class="mr-2 w-[165px]"
                @ok="(date) => console.log(date)"></a-date-picker>
              <span class="text-nowrap">年龄：</span>
              <a-input-number v-model:value="userForm.checkAge" :disabled="disableForm" :max="200" :min="0"
                class="w-fit"></a-input-number>
            </div>
            <div class="flex items-center">
              <span class="text-nowrap">检查时间：</span>
              <a-time-picker v-model:value="userForm.checkTime" :disabled="disableForm"
                class="mr-2 w-[300px]"></a-time-picker>
              <a-button @click="setCheckTime">获取时间</a-button>
            </div>
            <!-- <div class="flex items-center"> -->
            <!-- <span class="text-nowrap">检查部位：</span> -->

            <!--              <a-select-->
            <!--                style="width: 500px"-->
            <!--                :disabled="disableForm"-->
            <!--                v-model:value="userForm.checkPart"-->
            <!--              >-->
            <!--                <a-select-option value="ear">耳部</a-select-option>-->
            <!--                <a-select-option value="nose">鼻部</a-select-option>-->
            <!--                <a-select-option value="throat">咽喉部</a-select-option>-->
            <!--              </a-select>-->

            <!-- <a-cascader v-model:value="userForm.checkPart" :options="partOptions" style="width: 100%" -->
            <!-- @change="handlePartsChange"></a-cascader> -->
            <!-- </div> -->
          </div>
        </div>
        <div class="e-table p-2 h-[55%]">
          <div class="bg-white h-[490px] rounded-2xl p-2">
            <a-select v-model:value="selectValue" class="w-30 h-[20px] mb-4" default-active-first-option
              style="width: 140px">
              <a-select-option value="today">今日检查</a-select-option>
              <a-select-option value="yesterday">前一日检查</a-select-option>
            </a-select>
            <a-button @click="loadData(1)">获取检查列表</a-button>
            <a-table :columns="columns" :custom-row="clickThenSelect" :data-source="dataSource" :loading="tableLoading"
              :pagination="ipagination" :row-selection="{
                selectedRowKeys: state.selectedRowKeys,
                onChange: onSelectChange,
                type: 'radio'
              }" row-key="checkSerial" size="small" @change="handleTableChange">
              <template #status="{ record }">
                <a-tag v-if="record.checkStatus === 2" color="green">检查完成</a-tag>
                <a-tag v-else-if="record.checkStatus === 1" color="red">检查中</a-tag>
                <a-tag v-else-if="record.checkStatus === 0" color="orange">待检查</a-tag>
              </template>
            </a-table>
          </div>
        </div>
      </div>
      <!--          完成的图片和视频区--begin-->
      <div class="e-media h-[220px] p-2 flex overflow-hidden items-center gap-2 absolute bottom-[16px] left-[6px]">
        <div ref="mediaArea" :style="boxWidth"
          class="bg-white w-[450px] overflow-hidden items-center min-h-[200px] rounded-2xl flex relative z-[3] p-[20px] gap-[36px]">
          <div v-for="(item, index) in userForm.imageUrlArray" :key="index" class="size-[180px] flex-shrink-0">
            <a-image v-if="item.image_url" :src="item.image_url" alt="" class="rounded-full max-w-full h-full" />
            <a-image v-if="item.ai_image_url" :src="item.ai_image_url" alt="" class="rounded-full max-w-full h-full" />
            <video v-if="item.video_url" :poster="item.videoPoster" :src="item.video_url"
              class="rounded-full max-w-full h-full" controls></video>
          </div>
        </div>

        <button :disabled="imgContainerDisabled"
          class="z-[3] h-[200px] w-[40px] rounded-2xl bg-white btn-icon text-[30px] flex items-center justify-center"
          @click="expandImgContainer">
          <img v-if="signal" class="scale-[1.4]" src="../assets/buttonIcon/expand.svg" />
          <img v-else class="scale-[1.4] rotate-180" src="../assets/buttonIcon/expand.svg" />
        </button>
      </div>
      <!--          完成的图片和视频区--end-->
      <!--          表单和table区--end-->
      <!--          摄像头区--begin-->
      <div class="e-two w-2/4 relative">
        <div v-show="originalFeed !== ''"
          class="e-camera z-[2] absolute size-[960px] rounded-full top-0 overflow-hidden flex items-center justify-center">
          <img ref="originImg" :src="originalFeed" alt="" class="size-[960px] scale-[1.1] rounded-full" />
        </div>
        <div class="e-black size-[960px] relative flex bg-black rounded-full items-center justify-center z-[1]">
          <loading-component v-show="originLoading" class="absolute" style="scale: 0.8"></loading-component>
          <div v-show="!originLoading" class="flex flex-col">
            <img alt="" src="../assets/camaraArea/cameraDisabled.png" />
            <button
              class="bg-white w-[16rem] h-[3rem] rounded-full flex gap-4 items-center justify-center translate-y-10"
              @click="startCamera">
              <span class="text-[1.5rem] font-bold">内镜检测</span>
              <img alt="" class="scale-[1.4]" src="../assets/camaraArea/cameraCheckLoading.svg" />
            </button>
            <button
              class="bg-white w-[16rem] h-[3rem] rounded-full flex gap-4 items-center justify-center translate-y-10"
              @click="uploadData">
              <span class="text-[1.5rem] font-bold">上传数据</span>
              <img alt="" class="scale-[1.4]" src="../assets/camaraArea/uploadData.svg" />
            </button>
          </div>
        </div>

        <div class="e-button flex flex-col gap-2 absolute right-0 bottom-[36px]">
          <button class="right-0  bg-transparent border-none" @click="generatePic">
            <img alt="" class="size-[75px]" src="../assets/camaraArea/cameraShot.svg" />
          </button>
          <button v-if="videoSignal" class="bg-transparent border-none" @click="startVideo">
            <img alt="" class="size-[75px]" src="../assets/camaraArea/video.svg" />
          </button>
          <button v-else class="bg-transparent border-none" @click="stopVideo">
            <img alt="" class="size-[75px]" src="../assets/camaraArea/stopVideo.svg" />
          </button>
          <!--          <button @click="stopVideo" class="">-->
          <!--            <img class="max-w-full max-h-full" src="../assets/camaraArea/videoPlay.png" alt=""/>-->
          <!--          </button>-->
        </div>

        <button v-show="originalFeed !== ''" class="e-pause absolute -top-5 left-[80px] bg-transparent border-none"
          @click="shutdownCamera">
          <img alt="" class="size-[80px]" src="../assets/camaraArea/cameraPause.svg" />
        </button>
        <div v-show="!videoSignal" class="recording">

        </div>
      </div>
      <!--          摄像头区--end-->
      <!--                ai区--begin-->
      <div class="e-three w-1/4 flex flex-col ">
        <div class="h-1/2">
          <div class="e-ai-video w-[480px] h-[480px] rounded-full relative">
            <!--            黑色圆-->
            <div class="w-[480px] h-[480px] bg-black rounded-full z-[1] flex items-center justify-center">
              <loading-component v-show="aiLoading" class="absolute" style="scale: 0.8"></loading-component>
            </div>
            <!--            视频上层div-->
            <div v-show="isAiOpen" class="absolute w-auto h-[480px] z-[2] rounded-full overflow-hidden top-0">
              <!--              耳镜视频-->
              <img v-show="isEar" ref="aiEarFeedImg" :src="aiEarFeed" alt="" class="scale-[1.1] rounded-full" />
              <!--              鼻镜视频-->
              <img v-show="!isEar" ref="aiNoseFeedImg" :src="aiNoseFeed" alt="" class="scale-[1.1] rounded-full" />
            </div>
            <!--            播放按钮-->
            <button v-show="!isAiOpen" class="absolute -top-[10px] -left-[10px] bg-transparent border-none">
              <img alt="" class="size-[80px] z-9999 bg-transparent border-none" src="../assets/aiArea/aiVideoPlay.svg"
                @click="getAiFeed" />
            </button>
            <!--            暂停按钮-->
            <button v-show="isAiOpen" class="absolute -top-[10px] -left-[10px] bg-transparent border-none">
              <img alt="" class="size-[80px] z-9999" src="../assets/camaraArea/cameraPause.svg" @click="pauseAiFeed" />
            </button>
          </div>

        </div>
        <div class="e-result p-2 flex flex-col gap-[16px] h-1/2">
          <div class="h-1/4 flex relative items-center">
            <div class="w-1/3 justify-center flex relative items-center">
              <div
                class="border-2 rounded-full absolute size-[123px] border-[#02ECED] border-solid left-[25px] items-center justify-center flex">
              </div>
              <div class="absolute left-[27px]">
                <img v-if="firstImg" :src="firstImg" alt="" class="rounded-full size-[119px]" />
              </div>
            </div>
            <div class="w-1/3  justify-center flex relative items-center">
              <div
                class="border-2 rounded-full absolute size-[123px] border-[#02ECED] border-solid left-[25px] items-center justify-center flex">
              </div>
              <img v-show="secondImg" :src="secondImg" alt=""
                class="absolute z-[2] right-[8px] max-w-full rounded-full size-[119px]">
              <!--              <img :src="aiResultImg" alt="">-->
            </div>
            <div class="w-1/3  justify-center flex relative items-center">
              <div
                class="border-2 rounded-full absolute size-[123px] border-[#02ECED] border-solid left-[25px] items-center justify-center flex">
              </div>
              <img v-show="thirdImg" :src="thirdImg" alt=""
                class="absolute z-[2] right-[8px] max-w-full size-[119px] rounded-full">
              <!--              <img :src="aiResultImg" alt="">-->
            </div>
            <img alt="" class="scale-[0.6] absolute -left-2" src="../assets/aiArea/frameLeft.png" />
            <img alt="" class="scale-[0.6] absolute -right-6" src="../assets/aiArea/frameRight.png" />
          </div>
          <div class="h-2/4">
            <div class="bg-[#2a3877] size-full p-2 overflow-hidden">
              <span class="text-[26px] text-[white]">内镜所见：</span>
              <a-textarea v-model:value="insideCamera" class="mt-2 text-[18px]" placeholder="" style="height: 90%" />
            </div>
          </div>
          <div class="overflow-hidden flex justify-between items-center px-4">
            <button class="h-[70px] w-[200px] rounded-full border-none bg-cover" @click="generateAiImage">
              <img alt="" class="max-h-full max-w-full block m-auto scale-[1.1]" src="../assets/aiArea/aiButton.png" />
            </button>
            <button
              class="h-[70px] w-[200px] aiGenerateReport rounded-full bg-transparent border-none flex justify-center items-center"
              @click="generateAiReport">
              <img alt="" class="max-h-full max-w-full block m-auto scale-[0.7]" src="../assets/aiArea/aiText.png" />
              <span class="-translate-x-[24px] text-white text-[18px]">报告生成</span>
            </button>
          </div>
        </div>
      </div>
      <!--                ai区--end-->
    </div>
    <doctor-register ref="doctorRegister"></doctor-register>
    <doctor-edit ref="doctorEdit"></doctor-edit>
    <doctor-delete ref="doctorDelete"></doctor-delete>
    <search-patient ref="searchPatient"></search-patient>
    <report-print :id="userId" ref="reportPrint" :aiImageDataSource="aiImageDataSource" :doctor="doctor"
      :inside-camera-text="insideCamera" :normalImageDataSource="normalImageDataSource" :user="userForm"></report-print>
    <hospital-edit ref="hospitalEdit"></hospital-edit>

  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from 'vue'
import dayjs from 'dayjs'
import axios from 'axios'
import API_BASE_URL from '../config'
import { useStore } from 'vuex'
import { message, Modal, notification } from 'ant-design-vue'
import { closeWindow } from '../utils/electronUtils'
import { useRouter } from 'vue-router'
import { userTableDataTemplate } from './dataTemplate/userTable'
import { calculateBirthYearMonth, generateCheckSerial, generateNowDate, generateNowTime } from '../utils/tools'
import gsap from 'gsap'
import LoadingComponent from "./LoadingComponent.vue";
import { SettingOutlined, UserOutlined, LogoutOutlined, HomeOutlined } from '@ant-design/icons-vue';
import DoctorRegister from "./doctor/DoctorRegister.vue";
import DoctorEdit from "./doctor/DoctorEdit.vue";
import DoctorDelete from "./doctor/DoctorDelete.vue";
import SearchPatient from "./SearchPatient.vue";
import ReportPrint from "./Print/ReportPrint.vue";
import HospitalEdit from "./hospital/HospitalEdit.vue";


const isSaving = ref(false); // 在setup顶部添加
const store = useStore()
const router = useRouter()

const doctor = reactive({
  name: store.state.doctorInfo.doctorName,
  id: store.state.doctorInfo.doctorId,
})
watch(() => store.state.doctorInfo.doctorName, (newValue, oldValue) => {
  doctor.name = newValue
})


const doctorRegister = ref(null)
const addDoctor = () => {
  doctorRegister.value.showModal()
}
const doctorEdit = ref(null)
const updateDoctor = () => {
  doctorEdit.value.showModal()
}

const doctorDelete = ref(null)
const delDoctor = () => {
  doctorDelete.value.showModal()
}


const getHospitalInfo = () => {
  axios.get(`${API_BASE_URL}/hospital/list`).then((res) => {
    console.log('获取医院信息', res.data.data)
    console.log('获取医院名称', store.state.HospitalInfo.hospitalName)

    store.commit('setHospitalInfo', res.data.data)
  })
}
onMounted(getHospitalInfo)
const hospitalEdit = ref(null)
const editHospital = () => {
  console.log('hospitalEdit.value.open', hospitalEdit.value.open)
  hospitalEdit.value.showModal()
}
const handleSettingMenuClick = (value) => {
  const { key } = value
  if (key === '1') {
    editHospital()
  }
  if (key === '2') {
    logout()
  }
}
const handlePatientMenuClick = (value) => {
  const { key } = value
  if (key === '1') {
    addPatient()
  }
  if (key === '2') {
    editPatient()
  }
  if (key === '3') {
    deletePatient()
  }
  if (key === '4') {
    savePatient()
  }
}

// 处理检查部位菜单
const handleCheckMenuClick = (value) => {
  const { key } = value
  if (key === '1') {
    userForm.checkPart = ['耳部']
  }
  if (key === '2') {
    userForm.checkPart = ['鼻部']
  }
  if (key === '3') {
    userForm.checkPart = ['咽喉部']
  }
  // 如果需要，可以在这里添加部位变更后的其他逻辑
}

const disableForm = ref(false)

const tableLoading = ref(false)


/**
 * 添加患者
 */
const addPatient = () => {

  userForm.checkAge = null
  userForm.checkName = null
  // userForm.checkPart = ''
  userForm.checkPart = '';
  userForm.checkSex = '男'
  userForm.checkStatus = null
  userForm.imageUrlArray = []
  userForm.checkId = null
  userForm.userId = null
  userForm.checkSerial = generateCheckSerial()
  userForm.checkDate = generateNowDate()
  userForm.checkTime = generateNowTime()
  userForm.checkDoctorId = doctor.id
  disableForm.value = false

  onClearSelected()
}
const partOptions = [
  {
    value: '耳部',
    label: '耳部'
  },
  {
    value: '鼻部',
    label: '鼻部'
  },
  {
    value: '咽喉部',
    label: '咽喉部'
  },
];

const handlePartsChange = (value) => {
  userForm.checkPart = [...value]
  // console.log('userForm.checkPart[0]', userForm.checkPart[0])
  if (userForm.checkPart[0] === '耳部') {
    axios.get(`${API_BASE_URL}/get-ai-result`).then((res) => {
      if (res.data.code === 200) {
        console.log('内镜所见', res.data.message)
        handleEarAiResult(res.data.data)
      }
      if (res.data.code === 400) {
        message.error('AI检测超时，无法检测到耳道')
      }

    })
  }
};

const editPatient = () => {
  disableForm.value = !disableForm.value

  // axios.get(`${API_BASE_URL}`)
}

const deletePatient = () => {
  console.log('执行删除用户', userForm.checkId)
  if (!userForm.checkId) {
    message.warn('请先选择用户！')
    return
  }
  Modal.confirm({
    title: '确认删除？',
    content: '删除后不可恢复！',
    okText: '确认',
    cancelText: '取消',
    onOk() {
      axios.delete(`${API_BASE_URL}/delete-check`, {
        params: {
          checkId: userForm.checkId
        }
      }).then((res) => {
        if (res.data.code === 200) {
          message.success('删除成功！')
          addPatient()
          loadData(1)
        } else if (res.data.code === 404) {
          message.error('删除失败！记录不存在')
          console.log(res.data.message)
        } else {
          console.log(res.data.message)
        }
      })
    }
  })

}

const savePatient = async () => {
  if (isSaving.value) return;
  isSaving.value = true;

  try {
    if (!userForm.checkName || !userForm.checkAge || !userForm.checkSex || !userForm.checkPart) {
      message.warn('请填写完整信息！');
      return;
    }
    debugger
    const formData = new FormData();
    formData.append('checkSerial', userForm.checkSerial);
    formData.append('parts', userForm.checkPart.join(',')); // 添加这行
    formData.append('userName', userForm.checkName);
    formData.append('userGender', userForm.checkSex);
    formData.append('userAge', userForm.checkAge);
    formData.append('userBirthday', calculateBirthYearMonth(userForm.checkAge, dayjs().format('YYYY-MM-DD')));
    formData.append('checkTime', userForm.checkTime.format('YYYY-MM-DD HH:mm:ss'));
    formData.append('doctorId', store.state.doctorInfo.doctorId);
    formData.append('suggestion', userForm.suggestion); // 新增

    const res = await axios.post(`${API_BASE_URL}/generate-check`, formData);
    console.log('执行保存用户', `返回的信息是：${res.data.message}`);

    if (res.data.code === 200) {
      message.success('保存成功！');
      await loadData(1); // 等待数据加载完成
      // 不要在这里调用 addPatient()
    } else if (res.data.code === 409) {
      await updatePatient(); // 确保updatePatient不会递归调用savePatient
    } else {
      message.error('网络错误');
    }
  } catch (error) {
    console.error('保存失败:', error);
  } finally {
    isSaving.value = false;
  }
}

const updatePatient = () => {
  let formData = new FormData()
  formData.append('checkId', userForm.checkId)
  formData.append('checkSerial', userForm.checkSerial)
  formData.append('userName', userForm.checkName)
  formData.append('userGender', userForm.checkSex)
  formData.append('userAge', userForm.checkAge)
  formData.append('parts', userForm.checkPart)
  formData.append('userBirthday', calculateBirthYearMonth(userForm.checkAge, dayjs().format('YYYY-MM-DD')))
  let checkTime = userForm.checkDate.format('YYYY-MM-DD') + userForm.checkTime.format(' HH:mm:ss')
  formData.append('checkTime', checkTime)
  formData.append('suggestion', userForm.suggestion); // 新增
  axios.put(`${API_BASE_URL}/update-check`, formData).then((res) => {
    if (res.data.code === 200) {
      message.success('更新成功！')
      loadData(1)
    } else if (res.data.code === 409) {
      message.error('网络错误')
    } else {
      message.error('检测记录不存在')
    }
  })
}
let normalPicCount = 0
const generatePic = () => {
  if (userForm.checkStatus === 2) {
    message.warn('检测已完成')
    return
  }
  if (!userForm.checkPart) {
    message.warn('请选择部位')
    return;
  }
  console.log('执行生成图片')
  axios.get(`${API_BASE_URL}/generate-pic`, {
    params: {
      checkId: userForm.checkId
    },
  })
    .then((res) => {
      console.log('执行生成图片' + `返回的信息是:`, res)
      if (res.data.code === 0) {
        message.success('生成成功！')
        userForm.imageUrlArray.unshift({
          image_url: res.data.data.image_url,
          part: userForm.checkPart[1],
        })
        normalPicCount += 1
        if (normalPicCount === 1) {
          firstImg.value = res.data.data.image_url
        }
        if (normalPicCount === 2) {
          secondImg.value = res.data.data.image_url
        }
        if (normalPicCount === 3) {
          thirdImg.value = res.data.data.image_url
          normalPicCount = 0
        }
      } else {
        notification.error({
          message: '生成失败',
          description: '请先选择患者',
          duration: 2,
        })
        console.log(res.data.message)
      }
    })
}
const generateCheckRecord = () => {
  console.log('执行生成检查记录')
  let fromData = new FormData()
  userForm.checkSerial = generateCheckSerial()
  fromData.append('number', userForm.checkSerial)
  fromData.append('user_id', userForm.userId)
  axios.post(`${API_BASE_URL}/generate-check`, fromData)
    .then((res) => {
      console.log('执行生成检查记录', `返回的检测记录id是：${res.data.data.check_id}`)
      if (res.data.code === 0) {
        // userForm.checkId = res.data.data.check_id
        // generatePic()
      } else if (res.data.code === 1005) {
        // userForm.checkId = userForm.userId
        // generatePic()
      } else {
        message.error(res.data.message)
      }
      // console.log('userForm.checkId', userForm.checkId)
    })
}
const generateAiReport = () => {
  const target = dataSource.value.find(item => item.checkId === userForm.checkId)
  if (target.checkStatus === 0) {
    notification.warn({
      message: '生成报告失败',
      description: '请先生成AI图片',
      duration: 2,
    })
    return
  }


  let formData = new FormData()
  let report = {
    image: [],
    check_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
  }
  for (let i = 0; i < userForm.imageUrlArray.length; i++) {
    let obj = {
      image_url: userForm.imageUrlArray[i].image_url,
      video_url: userForm.imageUrlArray[i].video_url,
      ai_image_url: userForm.imageUrlArray[i].ai_image_url,
      part: userForm.imageUrlArray[i].part
    }
    report.image.push(obj)
  }
  formData.append('check_id', userForm.checkId)
  formData.append('report', JSON.stringify(report))
  axios.post(`${API_BASE_URL}/end-check`, formData).then((res) => {
    if (res.data.code === 200) {
      // message.success('生成报告成功！')
      notification.success({
        message: '生成报告',
        description: '生成报告成功',
        duration: 2,
      })
      loadData(1)
    } else {
      message.warn('报告已生成', res.data.message, 2)
      notification.warn({
        message: '生成报告失败',
        description: '报告已生成',
        duration: 2,
      })
      loadData(1)
      console.log(res.data.message)
    }
  })
}


const generateAiImage = () => {
  if (!userForm.checkId) {
    message.error('请先选择患者')
    return
  }
  const target = dataSource.value.find(item => item.checkId === userForm.checkId)
  if (target.checkStatus === 2) {
    message.warn('检测已完成')
    return;
  }
  target.checkStatus = 1
  if (typeof userForm.checkPart === 'string') {
    userForm.checkPart = [userForm.checkPart]
  }

  if (userForm.checkPart[0] === '耳部') {
    generateEarAi()
  }
  if (userForm.checkPart[0] === '鼻部') {
    generateNoseAi()
  }

}

function generateEarAi() {

  axios.get(`${API_BASE_URL}/generate-pic`, {
    params: {
      checkId: userForm.checkId,
      needAi: 1
    }
  }).then((res) => {
    if (res.data.code === 404) {
      notification.error({
        message: '生成失败',
        description: '生成失败,检测记录不存在',
        duration: 2,
      })
      console.log(res.data.message)
    }
    if (res.data.code === 400) {
      notification.error({
        message: '生成失败',
        description: res.data.message,
        duration: 2,
      })
    }
    if (res.data.code === 401) {
      notification.warning({
        message: '生成失败',
        description: '本次检测已完成',
        duration: 2,
      })
      console.log(res.data.message)
    }
    if (res.data.code === 1) {
      notification.warning({
        message: '生成成功',
        description: '未识别到耳部',
        duration: 2,
      })
      return
    }
    if (res.data.code === 2) {
      if (res.data.data.ai_result.code === 'GM_Not_Exist') {
        notification.warning({
          message: '生成失败',
          description: '未识别到鼓膜',
          duration: 2,
        })
        userForm.imageUrlArray.unshift({
          AiImageUrl: res.data.data.ai_image_path
        })
        return;
      }

      message.success('生成AI图片成功！')
      score.value = res.data.data.ai_result.Score
      userForm.imageUrlArray.unshift({
        ai_image_url: res.data.data.ai_image_path,
        part: userForm.checkPart[1]
      })
    }
    console.log('执行生成AI图片', `返回的信息是:`, res)
  })
}

const noseFeatures = {
  AH: "可见腺样体体积增大",//腺样体肥大
  AR: "可见鼻粘膜苍白，水肿",//变应性鼻炎
  CRP: "可见粘膜增厚，息肉形成或粘膜下的囊肿",//慢性鼻窦炎
  DNS: "鼻中隔（分隔两个鼻孔的骨头和软骨结构）向一侧或双侧偏曲",//鼻中隔偏曲
  NOR: "正常",
  NPC: "可见肿块或肿胀，可能有溃疡或表面粗糙",//鼻咽癌
  RHI: "可见鼻粘膜充血和水肿"//鼻窦炎
}
const generateNoseAi = () => {
  const formData = new FormData()
  formData.append('checkId', userForm.checkId)
  axios.post(`${API_BASE_URL}/gen-nose-hot-pic`, formData).then((res) => {
    if (res.data.code === 200) {
      // 加载图片和部位
      message.success('生成AI图片成功！')
      userForm.imageUrlArray.unshift({
        ai_image_url: res.data.data.hotImageUrl,
        part: userForm.checkPart[1]
      })
      handleNoseResult(res.data.data)

    } else {
      notification.error({
        message: '生成失败',
        description: res.data.message,
        duration: 2,
      })
      console.log(res.data.message)
    }
  })
}


const videoSignal = ref(true)
const videoFeed = ref('')
const startVideo = () => {
  videoSignal.value = false
  console.log('开始录制视频')
  if (!userForm.checkId) {
    message.error("请先选择患者")
    return
  }
  let videoPoster = ''
  axios.get(`${API_BASE_URL}/start-video`, {
    params: {
      checkId: userForm.checkId
    }
  }).then((res) => {
    videoFeed.value = res.data.data.vedio_info.url
    userForm.imageUrlArray.unshift({
      video_url: res.data.data.vedio_info.url,
    })
    message.success('保存视频成功！')
  })

}
const stopVideo = () => {
  axios.get(`${API_BASE_URL}/stop-video`).then((res) => {
    console.log(res)
  })
  videoSignal.value = true
}

const firstImg = ref()
const secondImg = ref()
const thirdImg = ref()


const clickThenSelect = (record) => {
  return {
    onClick: () => {
      onSelectChange(record.checkSerial.split(','), [record])
      // onSelectChange('', [record])
    }
  }
}

const selectValue = ref('today')

const setCheckTime = () => {
  console.log('执行设置检查时间', generateNowTime())
  let a = generateNowTime()
  userForm.checkTime = a
}

onMounted(() => {
  userForm.checkDate = generateNowDate()
  userForm.checkSerial = generateCheckSerial()
  userForm.checkTime = generateNowTime()
})


const userForm = reactive({
  userId: '',//用户id
  checkId: '',//检查记录ID
  checkSerial: '',
  checkName: '',
  checkSex: '',
  checkDate: '',
  checkTime: '',
  checkDoctorId: '',
  checkAge: null,
  checkPart: [],
  suggestion: '', // 新增建议字段
  checkStatus: 0,
  /**
   * 图片数组，包含一个对象
   * image_url,video_url,ai_image_url
   */
  imageUrlArray: []
})
const columns = userTableDataTemplate.columns

const dataSource = ref([])
const state = reactive({
  selectedRowKeys: [],
  selectedRows: []
})
const ipagination = reactive({
  current: 1,
  pageSize: 9,
  showTotal: (total, range) => {
    return range[0] + '-' + range[1] + ' 共' + total + '条'
  },
  total: 0
})
const onSelectChange = (selectedRowKeys, selectedRows) => {
  state.selectedRowKeys = selectedRowKeys
  state.selectedRows = selectedRows

  const target = dataSource.value.find((row) => row.checkSerial === selectedRowKeys[0])

  userForm.checkAge = target.checkAge
  userForm.checkName = target.checkName
  userForm.checkSerial = target.checkSerial
  userForm.userId = target.userId
  userForm.checkRecordId = target.checkRecordId
  userForm.checkSex = target.checkSex
  userForm.checkId = target.checkId
  userForm.checkPart = target.checkPart
  // console.log('userForm.checkPart', userForm.checkPart)
  userForm.checkDate = target.checkDate
  userForm.checkTime = target.checkTime
  userForm.checkStatus = target.checkStatus
  userForm.suggestion = target.suggestion || ''; // 新增

  userForm.imageUrlArray = target.imageUrlArray
  console.log('userForm.imageUrlArray', userForm.imageUrlArray)

  if (userForm.imageUrlArray !== undefined) {
    let imgArr = userForm.imageUrlArray
    userForm.imageUrlArray = []
    for (let i = 0; i < imgArr.length; i++) {
      userForm.imageUrlArray.push({
        image_url: imgArr[i].image_url,
        video_url: imgArr[i].video_url,
        ai_image_url: imgArr[i].ai_image_url,
        part: imgArr[i].part,
      })
    }

  }

  sendImagesToReportPrint(userForm.imageUrlArray)
  disableForm.value = true
}

const onClearSelected = () => {
  state.selectedRowKeys = []
  state.selectedRows = []
}

// const loadData = (arg) => {
//   if (arg === 1) {
//     ipagination.current = 1
//   }
//   onClearSelected()
//   tableLoading.value = true

//   axios.get(`${API_BASE_URL}/get-check-list`, {
//     params: {
//       page: ipagination.current,
//       per_page: ipagination.pageSize,
//       sort: 'desc',
//       doctorId: store.state.doctorInfo.doctorId
//     }
//   })
//     .then((res) => {
//       if (res.data.code === 409 || res.data.code === 400) {
//         message.error('网络错误')
//       }
//       //设置数据
//       let data = []
//       data = res.data.data.items
//       const newData = []
//       if (!data) {
//         return
//       }
//       for (let i = 0; i < data.length; i++) {
//         let a = {}
//         // console.log(data[i].created_at)
//         let date = data[i].check_time
//         a.checkDate = dayjs(date)
//         a.checkTime = dayjs(date)
//         a.checkAge = data[i].user_age
//         a.checkSerial = data[i].check_serial
//         a.checkDoctorId = data[i].doctor_id
//         a.checkName = data[i].user_name
//         a.userId = data[i].user_id
//         a.checkSex = data[i].user_gender
//         a.checkStatus = data[i].status
//         a.checkId = data[i].id
//         a.checkPart = a.checkPart !== null ? data[i].parts.split(',') : ''
//         if (data[i].report.image !== undefined) {
//           a.imageUrlArray = data[i].report.image
//         } else {
//           a.imageUrlArray = []
//         }
//         newData.push(a)
//       }
//       dataSource.value = newData
//       //设置总数
//       ipagination.total = res.data.data.total_items
//       tableLoading.value = false
//       addPatient()
//     })
// }

const loadData = (arg) => {
  if (arg === 1) {
    ipagination.current = 1;
  }
  onClearSelected();
  tableLoading.value = true;

  axios.get(`${API_BASE_URL}/get-check-list`, {
    params: {
      page: ipagination.current,
      per_page: ipagination.pageSize,
      sort: 'desc',
      doctorId: store.state.doctorInfo.doctorId
    }
  })
    .then((res) => {
      if (res.data.code === 409 || res.data.code === 400) {
        message.error('网络错误');
      }
      let data = res.data.data.items || [];
      const newData = [];
      if (!data) {
        tableLoading.value = false;
        return;
      }
      for (let i = 0; i < data.length; i++) {
        let a = {};
        let date = data[i].check_time;
        a.checkDate = dayjs(date);
        a.checkTime = dayjs(date);
        a.checkAge = data[i].user_age;
        a.checkSerial = data[i].check_serial;
        a.checkDoctorId = data[i].doctor_id;
        a.checkName = data[i].user_name;
        a.userId = data[i].user_id;
        a.checkSex = data[i].user_gender;
        a.checkStatus = data[i].status;
        a.checkId = data[i].id;
        a.checkPart = data[i].parts ? data[i].parts.split(',') : '';
        a.suggestion = data[i].suggestion || ''; // 新增

        // 兼容新旧后端返回的 report 结构
        if (data[i].report) {
          // 优先用 image 字段（老结构）
          if (Array.isArray(data[i].report.image)) {
            a.imageUrlArray = data[i].report.image;
          }
          // 新结构，original_images + heatmap_images
          else if (
            Array.isArray(data[i].report.original_images) &&
            Array.isArray(data[i].report.heatmap_images)
          ) {
            a.imageUrlArray = data[i].report.original_images.map((item, idx) => {
              const image_url = item.image_url || item.ai_image_url || '';
              const heatmap_url =
                data[i].report.heatmap_images[idx]?.heatmap_url ||
                data[i].report.heatmap_images[idx]?.ai_heatmap_url ||
                '';
              return {
                image_url,
                heatmap_url,
                part: a.checkPart?.[0] || '未知部位',
                // isAI: !!item.ai_image_url,
                key: idx
              };
            });
          } else {
            a.imageUrlArray = [];
          }
        } else {
          a.imageUrlArray = [];
        }
        newData.push(a);
      }
      dataSource.value = newData;
      ipagination.total = res.data.data.total_items || 0;
      tableLoading.value = false;
      addPatient();
    })
    .catch((err) => {
      message.error('拉取数据失败');
      tableLoading.value = false;
    });
};

const handleTableChange = (pagination, filters, sorter) => {
  //分页、排序、筛选变化时触发
  //TODO 筛选
  console.log(pagination)
  ipagination.current = pagination.current

  loadData()
}
onMounted(() => {
  loadData(1)
})


const originalFeed = ref('')
const originLoading = ref(false);
const originImg = ref(null)
const startCamera = () => {
  originLoading.value = true;
  if (!originImg.value) {
    return
  }
  /**
   * 加载用户检查列表
   */
  axios.get(`${API_BASE_URL}/check-camera`).then((res) => {
    if (res.data.data.exist_flag) {
      originalFeed.value = `${API_BASE_URL}/get-original-feed`
    } else {
      message.error('未检测到内窥镜')
      originLoading.value = false;
    }
  })
  originImg.value.onload = () => {
    console.log('原始视频加载完成')
    originLoading.value = false;
  }
}

// 上传数据方法
const uploadData = async () => {
  if (!userForm.checkId) {
    message.error("请先选择患者");
    return;
  }

  const input = document.createElement('input');
  input.type = 'file';
  input.accept = 'image/*';
  input.multiple = true;
  input.webkitdirectory = false;

  input.onchange = async (e) => {
    const files = Array.from(e.target.files);

    if (files.length !== 6) {
      message.error('请选择6张图片');
      return;
    }

    const formData = new FormData();
    formData.append('checkId', userForm.checkId);

    files.forEach((file) => {
      formData.append('images', file);
    });

    try {
      message.loading('正在上传图片...', 0);

      const res = await axios.post(`${API_BASE_URL}/ear/upload-images`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      message.destroy();

      if (res.data.code === 200) {
        message.success('上传成功！');
        // 重点修正部分
        const reportData = res.data.data; // 这里直接取 data
        const originalImages = reportData.original_images || [];
        const heatmapImages = reportData.heatmap_images || [];
        const part = userForm.checkPart?.[0] || '未知部位';

        // 合成图片数据
        const newImages = originalImages.map((item, idx) => {
          const image_url = item.image_url || item.ai_image_url;
          const heatmap_url = heatmapImages[idx]?.heatmap_url || heatmapImages[idx]?.ai_heatmap_url;
          return {
            image_url: image_url?.startsWith('http') ? image_url : `${API_BASE_URL}${image_url}`,
            heatmap_url: heatmap_url?.startsWith('http') ? heatmap_url : `${API_BASE_URL}${heatmap_url}`,
            part,
            // isAI: !!item.ai_image_url,
            key: idx
          };
        });

        userForm.imageUrlArray = [...newImages];

        // 更新左下角显示的图片（取前3张）
        if (newImages.length > 0) firstImg.value = newImages[0].image_url;
        if (newImages.length > 1) secondImg.value = newImages[1].image_url;
        if (newImages.length > 2) thirdImg.value = newImages[2].image_url;

        sendImagesToReportPrint(newImages);

        userForm.reportData = reportData; // 如有需要
      } else {
        message.error(res.data.message || '上传失败');
      }
    } catch (error) {
      message.destroy();
      message.error('上传过程中出错');
      console.error('上传错误:', error);
    }
  };

  input.click();
};

const aiFeed = ref(false)
const aiEarFeed = ref('')
const aiNoseFeed = ref('')
const aiLoading = ref(false)
const aiEarFeedImg = ref(null)
const aiNoseFeedImg = ref(null)
/**
 控制AI识别显示 耳镜/鼻镜
 @type {ComputedRef<boolean>}
 */
const isEar = computed(() => {
  // console.log('isEar',isEar.value)
  return userForm.checkPart[0] === '耳部' ? true : false
})
/**
 * 检测AI识别是否开启
 * @type {ComputedRef<boolean>}
 */
const isAiOpen = computed(() => {
  return aiNoseFeed.value !== '' || aiEarFeed.value !== ''
})
const getAiFeed = () => {
  if (!originalFeed.value) {
    notification.error({
      message: '未识别到内窥镜',
      description: '请先开启内窥镜',
      duration: 1,
      placement: 'topRight'
    })
    return
  }
  if (!userForm.checkPart) {
    notification.error({
      message: '未选择检查部位',
      description: '请先选择检查部位',
      duration: 1,
      placement: 'topRight'
    })
    return;
  }
  aiLoading.value = true
  console.log('cancelSource', cancelSource)
  aiEarFeed.value = `${API_BASE_URL}/get-ai-feed`
  aiNoseFeed.value = `${API_BASE_URL}/get-ai-nose-feed`
  aiEarFeedImg.value.onload = () => {
    console.log('耳镜ai识别加载完成')
    aiLoading.value = false;
  }
  aiNoseFeedImg.value.onload = () => {
    console.log('鼻镜ai识别加载完成')
    aiLoading.value = false;
  }
}

let cancelSource = null;
/**
 * 暂停摄像头
 */
const pauseAiFeed = () => {
  aiNoseFeed.value = ''
  aiEarFeed.value = ''
  axios.get(`${API_BASE_URL}/pause-ai-feed`).then((res) => {
    if (res.data.code === 200) {
      message.success('暂停成功')
      console.log(res.data.message)
    }
  })
}


const shutdownCamera = () => {
  /**
   * 关闭摄像头
   */
  axios.get(`${API_BASE_URL}/shutdown-camera`).then((res) => {
    if (res.data.code === 0) {
      originalFeed.value = ''
      aiEarFeed.value = ''
      aiNoseFeed.value = ''
      aiLoading.value = false
      message.success('关闭内窥镜成功')
      console.log(res.data.message)
    }
  })
}
/**
 * 内镜所见的文本
 * @type {Ref<UnwrapRef<string>>}
 */
const insideCamera = ref("")
const insideCameraTextArray = []
/**
 * 标识当前检测的部位
 * @type {ComputedRef<*>}
 */
const part = computed(() => {
  return userForm.checkPart[1]
})
const insideCameraText = {
  'CK': '鼓膜穿孔',
  'CT': '锤突可见',
  'CX': '鼓膜出血',
  'DN': '可见耵聍',
  'FMW': '可见分泌物',
  'GHB': '可见钙化斑',
  'GM': '鼓膜轮廓清晰',
  'HPS': '鼓膜琥珀色',
  'MJ': '霉菌可见',
  'PH': '可见鼓膜偏红',
  'SH': '可见鼓膜深红',
  'ED': '耳道通畅'
}
/**
 * 处理AI结果文本，即内镜所见
 */
const handleEarAiResult = (res) => {
  let text = []
  for (let key of Object.keys(res)) {
    if (res[key].length !== 0 && key !== 'code') {
      text.push(key)
    }
  }
  // 如果GM和CT同时存在，那么把这两个删除，改为ED并排在第一位
  // 若只存在其中一个，那么把这个排在第一位
  if (text.includes('GM') && text.includes('CT')) {
    text.splice(text.indexOf('GM'), 1)
    text.splice(text.indexOf('CT'), 1)
    text.unshift('ED')
    text.unshift('CT')
    text.unshift('GM')
  } else if (text.includes('GM') || text.includes('CT')) {
    if (text.includes('GM')) {
      text.splice(text.indexOf('GM'), 1)
      text.unshift('GM')
    } else {
      text.splice(text.indexOf('CT'), 1)
      text.unshift('CT')
    }
  }
  let txt = ''
  for (let key of text) {
    txt += insideCameraText[key] + '，'
  }
  // 判断当前part是否已存在于文本数组中
  if (insideCameraTextArray.length !== 0) {
    let isExist = insideCameraTextArray.find((item) => item.includes(part.value))
    if (isExist === undefined) {
      insideCameraTextArray.push(part.value + '：' + txt.substring(0, txt.length - 1))
    } else {
      isExist = part.value + '：' + txt.substring(0, txt.length - 1)
    }
  } else {
    insideCameraTextArray.push(part.value + '：' + txt.substring(0, txt.length - 1))
  }
  insideCamera.value = insideCameraTextArray.join('\n')


}
const handleNoseResult = (res) => {
  let feature = res['predictResult']['feature']
  Object.keys(noseFeatures).forEach(key => {
    if (feature === key) {
      // 判断当前part是否已存在于文本数组中
      if (insideCameraTextArray.length !== 0) {
        let isExist = insideCameraTextArray.find((item) => item.includes(part.value))
        if (isExist === undefined) {
          insideCameraTextArray.push(part.value + '：' + noseFeatures[key])
        } else {
          isExist = part.value + '：' + noseFeatures[key]
        }
      } else {
        insideCameraTextArray.push(part.value + '：' + noseFeatures[key])
      }
    }
  })
  insideCamera.value = insideCameraTextArray.join('\n')
}

const closeWin = () => {
  closeWindow()
}

/**
 * 退出登录
 */
const logout = () => {
  router.push('/')
  message.success('退出登录成功!')
}


const mediaArea = ref(null)
let boxWidth = ref()
let signal = ref(true)
const imgContainerDisabled = ref(false)
const expandImgContainer = () => {
  // boxWidth.value = mediaArea.value.offsetWidth
  let startWidth = ref(450)
  let endWidth = ref(1070)
  if (signal.value) {
    gsap.to(startWidth, {
      value: 1070,
      duration: 1.5,
      ease: 'circ.out',
      onStart: () => {
      },
      onComplete: () => {
        signal.value = false
        //给mediaArea设置x方向的滚动条
        mediaArea.value.classList.add('mediaScroll')
      },
      onUpdate: () => {
        boxWidth.value = `width: ${startWidth.value}px;`
        // console.log('startWidth',startWidth.value)
      }
    })
  } else {
    gsap.to(endWidth, {
      value: 450,
      duration: 1.5,
      ease: 'circ.out',
      onStart: () => {
      },
      onComplete: () => {
        signal.value = true
        // console.log(signal.value)
        mediaArea.value.classList.remove('mediaScroll')
      },
      onUpdate: () => {
        boxWidth.value = `width: ${endWidth.value}px;`
        // console.log('endWidth',endWidth.value)
      }
    })
  }

}
const searchPatient = ref(null)
const openSearchModal = () => {
  searchPatient.value.showModal()
}
const reportPrint = ref(null)
const aiImageDataSource = reactive([])
const normalImageDataSource = reactive([])
let userId = ref(null)

const previewReport = () => {

  reportPrint.value.showModal()
}

/**
 * 给选图页面传递数据
 */
const sendImagesToReportPrint = (imageArray) => {
  let ai = []
  let normal = []
  let aiCount = 0;
  let normalCount = 0;
  imageArray.forEach(i => {
    if (i.ai_image_url) {
      let obj = {}
      obj.ai_image_url = i.ai_image_url
      obj.key = aiCount
      obj.part = i.part
      ai.push(obj)
      aiCount++;
    }
    if (i.image_url) {
      let obj = {}
      obj.image_url = i.image_url
      obj.key = normalCount
      obj.part = i.part
      normal.push(obj)
      normalCount++;
    }
  })
  userId.value = userForm.checkId
  aiImageDataSource.length = 0
  normalImageDataSource.length = 0
  Object.assign(aiImageDataSource, [...ai])
  Object.assign(normalImageDataSource, [...normal])
}


</script>

<style scoped>
.main-page {}

.shutdown {
  background-image: linear-gradient(rgb(255, 131, 131) 0%, rgb(255, 0, 0) 100%);
}

.aiGenerateReport {
  background-image: linear-gradient(rgb(24, 109, 178) 0%, rgb(36, 81, 170) 100%);
}

.imgContainerP {}

.mediaScroll {
  overflow-x: scroll;
}


.recording {
  width: 50px;
  height: 50px;
  border-radius: 9999px;
  background-color: red;
  position: absolute;
  top: 18px;
  right: 86px;
  animation: recording 1.5s infinite;
}

@keyframes recording {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0
  }

}
</style>
